﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System;
using YonYou.U8.IN.Framework.Views;
using YonYou.U8.IN.Framework.Actions;
using YonYou.U8.IN.Framework.Internals;
using YonYou.U8.IN.Utility;

namespace YonYou.U8.IN.Framework
{
	public class ViewAdvisor
	{
		private static ViewAdvisor _Advisor;

		private IDictionary<Type, AbstractView> _Views;

		public static ViewAdvisor Instance
		{
			get
			{
				if (_Advisor == null)
				{
					_Advisor = new ViewAdvisor();
				}
				return _Advisor;
			}
		}

		internal BizContext Context { get; set; }

		internal WorkBench WorkBench { get; set; }

		public Form MainForm
		{
			get
			{
				return WorkBench.MainForm;
			}
		}

		public event EventHandler<CancelEventArgs> Exiting;

		public event EventHandler<CancelEventArgs> PageSwitching;

		public ViewAdvisor()
		{
			_Views = new Dictionary<Type, AbstractView>();
		}

		internal void RegisterView(AbstractView view)
		{
			if (view != null)
			{
				Type type = view.GetType();
				if (!_Views.ContainsKey(type))
				{
					_Views.Add(type, view);
				}
			}
		}

		internal T QueryView<T>() where T : AbstractView
		{
			Type typeFromHandle = typeof(T);
			if (_Views.ContainsKey(typeFromHandle))
			{
				return _Views[typeFromHandle] as T;
			}
			return null;
		}

		internal void OpenEditor(Control control)
		{
			AbstractView abstractView = QueryView<LayoutView>();
			abstractView.ExecuteAction<LayoutAddView>(new object[2]
			{
			LayoutStyle.Editor,
			new EditorView(control)
			});
		}

		public void OpenEditor(INetControl NetControl)
		{
			Control control = NetControl.CreateControl(Instance.Context);
			if (control != null)
			{
				if (control is Form)
				{
					(control as Form).TopLevel = false;
					(control as Form).FormBorderStyle = FormBorderStyle.None;
					(control as Form).Dock = DockStyle.Fill;
					(control as Form).Visible = true;
					(control as Form).Tag = this;
					(control as Form).AutoScroll = true;
				}
				else
				{
					control.Dock = DockStyle.Fill;
					control.Visible = true;
					control.Tag = this;
				}
				OpenEditor(control);
			}
		}

		public void SetHelpUrl(string url)
		{
			if (string.IsNullOrEmpty(url))
			{
				throw new ArgumentNullException("url");
			}
			(MainForm as ViewBenchForm).SetHelpUrl(url);
		}

		internal void OnExiting(CancelEventArgs e)
		{
			if (this.Exiting != null)
			{
				this.Exiting(MainForm, e);
			}
		}

		internal void OnPageSwitching(CancelEventArgs e)
		{
			if (this.PageSwitching != null)
			{
				this.PageSwitching(MainForm, e);
			}
		}

		internal void ClearEvents()
		{
			this.Exiting = null;
			this.PageSwitching = null;
		}
	}

}